package com.crowdfunding.backend.security;

import io.jsonwebtoken.Claims;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

public class JwtAuthFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;

    public JwtAuthFilter(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String auth = request.getHeader("Authorization");
        if (auth != null && auth.startsWith("Bearer ")) {
            String token = auth.substring(7);
            try {
                Claims claims = jwtUtil.parseToken(token).getBody();
                String subject = claims.getSubject();
                if (subject != null) {
                    // create simple Authentication with user id as principal
                    UsernamePasswordAuthenticationToken a = new UsernamePasswordAuthenticationToken(subject, null, Collections.singleton(new SimpleGrantedAuthority("USER")));
                    SecurityContextHolder.getContext().setAuthentication(a);
                }
            } catch (Exception e) {
                // invalid token -> ignore and let security handle
            }
        }
        filterChain.doFilter(request, response);
    }
}
